//
//  CDImagePicker.m
//  CarDream
//
//  Created by lidi on 15/4/28.
//  Copyright (c) 2015年 colin. All rights reserved.
//

#import "CDImagePicker.h"
#import "RSKImageCropper.h"

@interface CDImagePicker()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,RSKImageCropViewControllerDelegate>
@property(copy , nonatomic) void (^completeBlock)(NSString *imagePath_);
@property(weak, nonatomic)UIViewController *handleViewCnotroller;
@property(strong, nonatomic)UIImagePickerController *imagePicker;
@end

@implementation CDImagePicker

+ (instancetype)imagePickerWith:(UIViewController *)viewController_
                           type:(UIImagePickerControllerSourceType)type_
                  completeBlock:(void (^)(NSString *))completeBlock_
{
    CDImagePicker *sharedCDImagePicker = [self new];
    sharedCDImagePicker.imagePicker = [[UIImagePickerController alloc] init];
    sharedCDImagePicker.imagePicker.sourceType = type_;
    sharedCDImagePicker.imagePicker.delegate = sharedCDImagePicker;
    sharedCDImagePicker.handleViewCnotroller = viewController_;
    sharedCDImagePicker.completeBlock = completeBlock_;
    
    return sharedCDImagePicker;
}

- (void)choose
{
    [self.handleViewCnotroller presentViewController:self.imagePicker animated:YES completion:^{
        
    }];
}

- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    [[UIApplication sharedApplication] setStatusBarHidden:NO];
}

#pragma mark 拍照选择照片协议方法
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    if ([mediaType isEqualToString:@"public.image"]){
        
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            
            NSData *data;
            //切忌不可直接使用originImage，因为这是没有经过格式化的图片数据，可能会导致选择的图片颠倒或是失真等现象的发生，从UIImagePickerControllerOriginalImage中的Origin可以看出，很原始，哈哈
            UIImage *originImage = [info objectForKey:UIImagePickerControllerOriginalImage];
            //图片压缩，因为原图都是很大的，不必要传原图
            UIImage *scaleImage=[self scaleImage:originImage toScale:0.5];
            //以下这两步都是比较耗时的操作，最好开一个HUD提示用户，这样体验会好些，不至于阻塞界面
            if (UIImagePNGRepresentation(scaleImage) == nil) {
                //将图片转换为JPG格式的二进制数据
                data = UIImageJPEGRepresentation(scaleImage, 1);
            } else {
                //将图片转换为PNG格式的二进制数据
                data = UIImagePNGRepresentation(scaleImage);
            }
            //将二进制数据生成UIImage
            UIImage *image = [UIImage imageWithData:data];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                //将图片传递给截取界面进行截取并设置回调方法（协议）
                RSKImageCropViewController *imageCropViewController = [[RSKImageCropViewController alloc] initWithImage:image cropMode:RSKImageCropModeCircle];
                imageCropViewController.delegate = self;
                [picker pushViewController:imageCropViewController animated:YES];
            });
        });
    }
}

#pragma mark  RSKImageCropViewController Delegate

- (void)imageCropViewControllerDidCancelCrop:(RSKImageCropViewController *)controller
{
    [controller.navigationController dismissViewControllerAnimated:YES completion:^{
        
    }];
}

- (void)imageCropViewController:(RSKImageCropViewController *)controller didCropImage:(UIImage *)croppedImage usingCropRect:(CGRect)cropRect rotationAngle:(CGFloat)rotationAngle
{
    __weak typeof(self) safe_self = self;
    
    NSString *imageName = [[[NSUUID alloc] init] UUIDString];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        [safe_self writeCache:croppedImage chacheName:imageName];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            //上传图片
            [controller.navigationController dismissViewControllerAnimated:YES completion:^{
                if (safe_self.completeBlock) {
                    safe_self.completeBlock([[safe_self cacheDirectory] stringByAppendingPathComponent:imageName]);
                }
            }];
        });
        
    });


}

#pragma mark - 缩放图片
- (UIImage *)scaleImage:(UIImage *)image toScale:(float)scaleSize
{
    UIGraphicsBeginImageContext(CGSizeMake(image.size.width*scaleSize,image.size.height*scaleSize));
    [image drawInRect:CGRectMake(0, 0, image.size.width * scaleSize, image.size.height *scaleSize)];
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaledImage;
}

- (NSString *)cacheDirectory
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES);
    return [paths objectAtIndex:0];
}

- (void)writeCache:(UIImage *)image_ chacheName:(NSString *)cacheName
{
    NSString *cachePath = [[self cacheDirectory] stringByAppendingPathComponent:cacheName];
    //图像压缩
    NSData *imageData = UIImageJPEGRepresentation(image_,.5f);
    [imageData writeToFile:cachePath atomically:YES];
}

@end
